﻿using System.Collections.Generic;
using System.Text.RegularExpressions;
using Obsidian.Data.Sql;
using Obsidian.Edm;
using [#ModelNS#];

/*============================
 * @author [#AUTHOR#]
 * @created [#CREATED#]
 * @desc 
* ============================ */

namespace [#DalNS#]
{
	/// <summary>
	/// [#ClsName#] 数据访问
	/// </summary>
	public class [#ClsName#]DA
	{
		#region [SELECT]
		internal [#ClsName#]Info SelectById([#IdSysType#] [#IdAlias#])
		{
			[#ClsName#]Info om = new [#ClsName#]Info();
			IDbHandler dbh = om.CreateHandler();
			dbh.SetFields(om.Fields);

			dbh.Where(om.[#IdName#].Equals([#IdAlias#]));

			DataReader dr = dbh.Select();
			om = dr.ReadFirst<[#ClsName#]Info>();
			return om;
		}		

		/// <summary>
		/// 通过查询实体查询记录列表
		/// </summary>
		/// <param name="qry">查询实体</param>
		/// <param name="la">列表特征（分页）实体</param>
		/// <returns></returns>
		internal List<[#ClsName#]Info> SelectList([#ClsName#]Qry qry, out ListAttrInfo la)
		{
			[#ClsName#]Info om = new [#ClsName#]Info();
			IDbHandler dbh = om.CreateHandler();
			dbh.SetFields(om.Fields);

			//组装日期时间条件
			string dtFormat = "yyyy-MM-dd HH:mm:ss";
			if (!qry.StartCreateDT.IsNull && (!qry.StartCreateDT.IsMinValue))
			{
				dbh.Where(om.CreateDT.Compare(">=", qry.StartCreateDT.Value.ToString(dtFormat)));
			}
			if (!qry.EndCreateDT.IsNull && (!qry.EndCreateDT.IsMinValue))
			{
				dbh.Where(om.CreateDT.Compare("<=", qry.EndCreateDT.Value.ToString(dtFormat)));
			}
			if (!qry.StartModifyDT.IsNull && (!qry.StartModifyDT.IsMinValue))
			{
				dbh.Where(om.ModifyDT.Compare(">=", qry.StartModifyDT.Value.ToString(dtFormat)));
			}
			if (!qry.EndModifyDT.IsNull && (!qry.EndModifyDT.IsMinValue))
			{
				dbh.Where(om.ModifyDT.Compare("<=", qry.EndModifyDT.Value.ToString(dtFormat)));
			}

			//组装记录ID（串）条件
			if (!qry.[#IdName#].IsNull)
			{
				dbh.Where(om.[#IdName#].Equals(qry.[#IdName#].Value));
			}
			if (!qry.[#IdName#]s.IsNull && qry.[#IdName#]s.Count > 0)
			{
				dbh.Where(om.[#IdName#].In(qry.[#IdName#]s.Value));
			}

			//过滤记录ID（串）条件
			if (!qry.FiltIds.IsNull && qry.FiltIds.Count > 0)
			{
				dbh.Where(om.[#IdName#].NotIn(qry.FiltIds.Value));
			}
			if (!qry.FiltIds.IsNull && qry.FiltIds.Count > 0)
			{
				dbh.Where(om.[#IdName#].NotIn(qry.FiltIds.Value));
			}

			//组装关键字条件（名称，标题，简介，详情）
			/*
			if (!qry.Keyword.IsNullOrWhiteSpace)
			{
				CompoundCondition cc = new CompoundCondition();    //复合条件类
				cc.Or(om.Name.Like(qry.Keyword.Value));
				dbh.Where(cc);
			}
			
			//多关键字条件（以英文逗号分隔）
			if (!qry.Keywords.IsNull && qry.Keywords.Count > 0)
			{
				CompoundCondition cc = new CompoundCondition();    //复合条件类
				for (int i = 0, j = qry.Keywords.Count; i < j; i++)
				{
					cc.Or(om.Name.Like(qry.Keywords.Value[i]));
				}
				dbh.Where(cc);
			}
			*/    
            
			//记录状态条件（如果有）
			/*
			if (!qry.Enabled.IsNull)
			{
				dbh.Where(om.Enabled.Equals(qry.Enabled.Value));
			}
			*/

			//组装JOIN条件（预留）

			//组装排序条件（！！放在Where子句最后，分页时，必须有OrderBy）
			if (!qry.OrderBy.IsNull && qry.OrderBy.Count > 0)
			{
				OrderInfo[] ois = qry.OrderBy.GetArray();
				foreach (OrderInfo oi in ois)
				{
					//case条件字段值需要和Query查询实体的OrderByFields属性一致
					switch (oi.FieldAlias.ToLower())	//排序字段别名转化为小写
					{
						/*
						case "sortorder":
							dbh.OrderBy(om.SortOrder, oi.OrderType);
							break;
						case "enabled":
							dbh.OrderBy(om.Enabled, oi.OrderType);
							break;
						case "createdt":
							dbh.OrderBy(om.CreateDT, oi.OrderType);
							break;
						case "modifydt":
							dbh.OrderBy(om.ModifyDT, oi.OrderType);
							break;
						*/
						case "[#IdAlias#]":
						default:
							dbh.OrderBy(om.[#IdName#], oi.OrderType);
							break;
					}
				}
			}
			else
			{
				dbh.OrderBy(om.[#IdName#], OrderType.DESC); //默认排序条件
			}
			//[END]::组装Where组合条件语句

			List<[#ClsName#]Info> list = new List<[#ClsName#]Info>();
			DataReader dr = dbh.Select(qry, out la);
			list = dr.ReadList<[#ClsName#]Info>();

			return list;
		}

		#endregion [SELECT]

		#region [EXISTS]
		
		/// <summary>
		/// 是否已存在同名记录（添加时判断）
		/// </summary>
		/// <param name="keyword">关键字</param>
		/// <param name="imField">实体字段接口</param>
		/// <returns></returns>
		internal bool ExistsBy(string keyword, IModelField imField)
		{
			[#ClsName#]Info om = new [#ClsName#]Info();
			IDbHandler dbh = om.CreateHandler();
			dbh.SetField(om.[#IdName#]);

			dbh.Where(imField.Equals(keyword));

			DataReader dr = dbh.Select();
			return dr.ReadFirst<[#ClsName#]Info>() != null;
		}

		/// <summary>
		/// 是否已存在不同ID的同名记录（修改时判断）
		/// </summary>
		/// <param name="[#IdAlias#]">记录ID</param>
		/// <param name="keyword">关键字</param>
		/// <param name="imField">实体字段接口</param>
		/// <returns></returns>
		internal bool ExistsBy([#IdSysType#] [#IdAlias#], string keyword,  IModelField imField)
		{
			[#ClsName#]Info om = new [#ClsName#]Info();
			IDbHandler dbh = om.CreateHandler();
			dbh.SetField(om.[#IdName#]);

			dbh.Where(imField.Equals(keyword));
			dbh.Where(om.[#IdName#].Compare("<>", [#IdAlias#]));

			DataReader dr = dbh.Select();
			return dr.ReadFirst<[#ClsName#]Info>() != null;
		}
		
		#endregion [EXISTS]
	}
}